package cn.cable.monitor.sdk.appender;

import ch.qos.logback.classic.spi.ILoggingEvent;
import ch.qos.logback.core.AppenderBase;
import cn.cable.monitor.sdk.model.LogMessage;
import cn.cable.monitor.sdk.push.IPush;
import cn.cable.monitor.sdk.push.impl.RedisPush;
import java.util.Arrays;

/**
 * 自定义日志采集
 *
 * @author hsj
 * @date 2024/7/16 14:47
 */
public class CustomAppender<E> extends AppenderBase<E> {

	//系统名称
	private String systemName;

	/**
	 * 只采集指定范围的日志
	 */
	private String groupId;

	/**
	 * redis连接地址
	 */
	private String host;

	/**
	 * 端口
	 */
	private int port;

	private String password;


	private final IPush push = new RedisPush();

	@Override
	protected void append(E eventObject) {
        //开启推送
		push.open(host,port,password);


		if (eventObject instanceof ILoggingEvent) {
			ILoggingEvent event = (ILoggingEvent) eventObject;
			String className = "unknown";
			String methodName = "unknown";

			StackTraceElement[] callerDataArray = event.getCallerData();

			if (null != callerDataArray && callerDataArray.length > 0) {
				StackTraceElement callerData = callerDataArray[0];
				methodName = callerData.getMethodName();
				className = callerData.getClassName();
			}

			if (!className.startsWith(groupId)){
				return;
			}

			//构建日志
			LogMessage logMessage = new LogMessage(systemName, className, methodName, Arrays.asList(event.getFormattedMessage().split(" ")));
			//推送日志
	        push.send(logMessage);
		}

	}

	public String getSystemName() {
		return systemName;
	}

	public String getGroupId() {
		return groupId;
	}

	public String getHost() {
		return host;
	}

	public int getPort() {
		return port;
	}

	public void setSystemName(String systemName) {
		this.systemName = systemName;
	}

	public void setGroupId(String groupId) {
		this.groupId = groupId;
	}

	public void setHost(String host) {
		this.host = host;
	}

	public void setPort(int port) {
		this.port = port;
	}

	public String getPassword() {
		return password;
	}

	public void setPassword(String password) {
		this.password = password;
	}

}
